package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: Dgg
 * @Date: 2021/11/30 22:40
 */
public class NIOServer {
	public static void main(String[] args) throws IOException {
		//创建ServerSocketChannel -> serverSocket
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

		//得到一个selector对象
		Selector selector = Selector.open();

		//绑定端口
		serverSocketChannel.socket().bind(new InetSocketAddress(6666));
		//设置为非阻塞
		serverSocketChannel.configureBlocking(false);

		//把serverSocketchannel注册到selector 关心事件OP_ACCEPT
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("注册后的selector数量" + selector.keys().size());
		//循环等待客户端链接
		while (true) {
			//这里等待1s，没有事件发生，返回
			if (selector.select(1000) == 0) {
				System.out.println("服务器等待1s无连接");
				continue;
			}
			//如果返回的大于0,表示已经获取到关注的事件
			//获取到相关 的 selection集合
			//selector.selectedKeys() 返回关注事件的集合
			//通过selectionKeys 反向获取通道
			Set<SelectionKey> selectionKeys = selector.selectedKeys();

			//遍历 selectionKeys
			Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
			System.out.println("事件发生的selectionKey" + keyIterator);
			while (keyIterator.hasNext()) {

				SelectionKey key = keyIterator.next();
				//根据key对应的通道 发生的事件 做相应的处理
				if (key.isAcceptable()) {//如果是 OP_ACCEPT，有一个新的客户端链接
					//给该客户端生成socketchannel
					SocketChannel accept = serverSocketChannel.accept();
					accept.configureBlocking(false);
					//将socketCahnnel注册到selector 关注事件为OP_READ 同时给socketchannel 关联一个buffer
					accept.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(18));
					System.out.println("客户端连接后注册的selectorKey数量：" + selector.keys().size());

				}
				if (key.isReadable()) {//发生 OP_READ
					//通过key 反向获取到对应的channel
					SocketChannel channel = (SocketChannel) key.channel();
					// 获取到该channel 关联的buffer
					ByteBuffer buffer = (ByteBuffer) key.attachment();
					//读取当前通道中的 buffer 数据
					channel.read(buffer);
					System.out.println("from 客户端:" + new String(buffer.array()));
				}
				//手动从集合中移除当前的selectionKey,防止重复操作

				keyIterator.remove();
			}
		}

	}
}
